package com.play.ballen.pack.ui

import android.os.Bundle
import android.widget.Button
import androidx.recyclerview.widget.GridLayoutManager
import com.hjq.toast.ToastUtils
import com.play.ballen.R
import com.play.ballen.databinding.FragmentPackChildBinding
import com.play.ballen.event.EventCost
import com.play.ballen.mall.entity.MallBallLevel
import com.play.ballen.me.dialog.OperateSuccessDialogUtils
import com.play.ballen.pack.adapter.PackBallAdapter
import com.play.ballen.pack.dialog.PackSaleDialogUtils
import com.play.ballen.pack.entity.PackBallInfo
import com.play.ballen.pack.vm.PackVM
import com.play.ballen.view.BaseHeaderView
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.yuven.appframework.widget.SpacesItemDecoration
import com.yuven.baselib.component.BaseMVVMFragment
import com.yuven.baselib.component.eventbus.Event
import com.yuven.baselib.component.eventbus.EventBusUtil
import com.yuven.baselib.utils.ResourceUtil
import com.yuven.baselib.utils.ViewUtils
import com.yuven.baselib.widget.MultiStateView

class PackChildFragment : BaseMVVMFragment<PackVM, FragmentPackChildBinding>() {

    private var isVisibleToUser = false    //是否可见
    private var isPrepared = false //布局是否准备好

    private val adapter: PackBallAdapter by lazy {
        PackBallAdapter(arrayListOf())
    }
    private var curEntity: PackBallInfo? = null

    private var needReload = false  //是否需要重新加载布局
    private var type = ""

    var levelCallBack: ((items: List<MallBallLevel>?) -> Unit)? = null
    var getSelectLevelId: (() -> String)? = null
    var headerView: BaseHeaderView? = null

    private val operateSuccessDialogUtils by lazy { OperateSuccessDialogUtils(mContext) }
    private val packSaleDialogUtils by lazy {
        PackSaleDialogUtils(mContext).apply {
            valuesCallback = { price, num ->
                viewModel.basketballSellConfirm(curEntity!!.id, price, num)
            }
        }
    }

    companion object {
        val TAG: String = PackChildFragment::class.java.simpleName

        fun newInstance(type: String): PackChildFragment {
            val args = Bundle().apply {
                putString("type", type)
            }
            val fragment = PackChildFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            type = it.getString("type", "")
        }
    }

    override fun initIntent() {}

    override fun layoutId(): Int {
        return R.layout.fragment_pack_child
    }

    override fun viewModelClass(): Class<PackVM> {
        return PackVM::class.java
    }

    override fun initObserver() {
        super.initObserver()

        viewModel.actionGetBallFailure.observe(this) {
            dataBinding.refreshLayout.finishRefresh()
            dataBinding.refreshLayout.finishLoadMore()
            if (viewModel.page == 1) {
                dataBinding.msvLayout.viewState = MultiStateView.VIEW_STATE_ERROR
            } else {
                ToastUtils.show(ResourceUtil.getString(R.string.load_fail))
            }
        }

        viewModel.listBall.observe(this) {
            dataBinding.refreshLayout.finishRefresh()
            dataBinding.refreshLayout.finishLoadMore()

            if (!it.isNullOrEmpty()) {
                if (viewModel.page == 1) {
                    adapter.setList(it)
                    dataBinding.rv.scrollToPosition(0)
                    dataBinding.msvLayout.viewState = MultiStateView.VIEW_STATE_CONTENT
                } else {
                    adapter.addData(it)
                }
                viewModel.page++
            } else {
                //no data
                if (viewModel.page == 1) {
                    dataBinding.msvLayout.viewState = MultiStateView.VIEW_STATE_EMPTY
                } else {
                    ToastUtils.show(ResourceUtil.getString(R.string.load_end))
                }
            }
        }

        viewModel.listMallBallLevel.observe(this) {
            levelCallBack?.invoke(it)
        }

        viewModel.totalDestroy.observe(this) {
            headerView?.bindView(BaseHeaderView.TYPE_DESTROY_TOTAL, it)
        }

        viewModel.ballSellInfo.observe(this) {
            it?.let {
                packSaleDialogUtils.show(it.num.toInt(), it.fee, it.min_price)
            }
        }

        viewModel.actionSaleSuccess.observe(this) {
            operateSuccessDialogUtils.show(ResourceUtil.getString(R.string.pack_sale_success))
            //刷新
            notifyLevelChange()
            EventBusUtil.post(Event.create(EventCost.CODE_REFRESH_PACK_SALE))
        }

        viewModel.actionSaleCancelSuccess.observe(this) {
            //刷新
            notifyLevelChange()
            EventBusUtil.post(Event.create(EventCost.CODE_REFRESH_PACK_OWNER))
        }
    }

    override fun initView() {
        isPrepared = true

        dataBinding.msvLayout.findViewById<Button>(R.id.btnTryAgain).setOnClickListener {
            dataBinding.msvLayout.viewState = MultiStateView.VIEW_STATE_LOADING
            viewModel.memberBasketBall(type, getSelectLevelId?.invoke())
        }
    }

    override fun initData() {
        dataBinding.refreshLayout.setEnableLoadMore(true)
        dataBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                viewModel.page = 1
                viewModel.memberBasketBall(type, getSelectLevelId?.invoke())

            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                viewModel.memberBasketBall(type, getSelectLevelId?.invoke())
            }
        })

        dataBinding.rv.layoutManager = GridLayoutManager(mContext, 2)
        dataBinding.rv.addItemDecoration(SpacesItemDecoration(2, ViewUtils.dip2px(10f), true))
        dataBinding.rv.adapter = adapter
        adapter.type = type
        adapter.addChildClickViewIds(R.id.btn)
        adapter.setOnItemChildClickListener { a, view, position ->
            if (type == PackFragment.TYPE_PACK_DESTROY || type == PackFragment.TYPE_PACK_LAPSED) {
                return@setOnItemChildClickListener
            }

            curEntity = adapter.data[position]
            if (type == PackFragment.TYPE_PACK_OWNER) {
                viewModel.basketballSell(curEntity!!.id)
            }

            if (type == PackFragment.TYPE_PACK_SALE) {
                viewModel.basketballSellCancel(curEntity!!.id)
            }
        }

        //依次addHeaderView
        headerView?.let {
            val headers = it.views
            if (headers.isNotEmpty()) {
                headers.forEachIndexed { index, v ->
                    dataBinding.headerContainer.addView(v, index)
                }
            }
        }

        loadData()
    }

    private fun loadData() {
        if (isVisibleToUser) {
            if (isPrepared || needReload) {
                dataBinding.msvLayout.viewState = MultiStateView.VIEW_STATE_LOADING
                viewModel.page = 1
                viewModel.memberBasketBall(type, getSelectLevelId?.invoke())

                needReload = false
            }
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        this.isVisibleToUser = isVisibleToUser
        if (isVisibleToUser) {
            loadData()
        } else {
            isPrepared = false
        }
    }

    fun notifyLevelChange() {
        needReload = true

        if (isVisibleToUser) {
            loadData()
        }
    }

}